#! /bin/bash

function git_is_repo() {
    test -d .git || command git rev-parse --git-dir >/dev/null 2> /dev/null
}

function git_branch_name() {
    command git symbolic-ref --short HEAD 2> /dev/null || command git show-ref --head -s --abbrev | head -n1 2> /dev/null
}

function git_is_touched() {
    # The first checks for staged changes, the second for unstaged ones.
    # We put them in this order because checking staged changes is *fast*.  
    ! command git diff-index --cached --quiet HEAD -- >/dev/null 2>&1 || ! command git diff --no-ext-diff --quiet --exit-code >/dev/null 2>&1
}

function git_is_stashed() {
    command git rev-parse --verify --quiet refs/stash >/dev/null
}

# params: ahead, behind, diverged
function git_ahead() {
    local commit_count=$(command git rev-list --count --left-right "@{upstream}...HEAD" 2> /dev/null)

    case "$commit_count" in
        0$'\t'0) # none
            echo ""
            ;;
        0$'\t'*) # ahead
            test -n $1 && echo $1 || echo "+"
            ;;
        *$'\t'0) # behind
            test -n $2 && echo $2 || echo "-"
            ;;
        *) # diverged
            test -n $3 && echo $3 || echo "!"
            ;;
    esac
}
